<template>
    <div  >

        <el-card>
            <template #header>
                <h2>警员信息数据</h2>
            </template>

            <el-form inline>
                <el-form-item label="警员名">
                    <el-input v-model="searchParams.name" placeholder="请输入警员名" />
                </el-form-item>
                <el-form-item label="所属派出所" label-width="90px" prop="stationName">
                    <el-select v-model="searchParams.stationName" clearable placeholder="请输入所属派出所" style="width: 240px">
                        <el-option v-for="item in stationOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="fetchData">搜索</el-button>
                    <el-button type="default" @click="reset">重置</el-button>
                    <el-button type="default" @click="openAddUser">添加</el-button>
                </el-form-item>
            </el-form>
            <el-scrollbar height="400">
                <el-table :data="tableData">
                    <!-- 在officerId前面加一个labelP -->


                    <el-table-column prop="officerId" label="警号" width="80" >
                        <template #default="scope">
    <div>
      <el-tag type="primary">{{ 'P' + scope.row.officerId }}</el-tag>
    </div>
  </template>
</el-table-column>
                    <el-table-column prop="name" label="警员名" width="80" />
                    <el-table-column prop="phoneNumber" label="手机号" width="160" />
                    <el-table-column prop="gender" label="性别" :formatter="genderFormat" width="80" />
                    <el-table-column prop="birthDate" label="生日" :formatter="formatDate" />
                    <el-table-column prop="email" label="邮箱" />
                    <el-table-column prop="policeStation.name" label="所属派出所" width="100" />
                    <el-table-column prop="createdAt" label="创建时间" :formatter="formatDate" />
                    <el-table-column label="操作" width="200">
                        <template #default="scope">
                            <el-button type="success" size="small" @click="editUser(scope.row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="confirmDeleteUser(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

            </el-scrollbar>


            <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>




        <!-- 弹窗 -->
        <el-dialog v-model="dialogFormVisible" :title="title" width="800">
            <el-form :model="policeInfo" :rules="rules" ref="policeInfoForm">
                <el-form-item label="警员名" label-width="100px" prop="name">
                    <el-input v-model="policeInfo.name" />
                </el-form-item>
                <el-form-item label="性别" label-width="100px" prop="gender">
                    <el-select v-model="policeInfo.gender" placeholder="请选择性别" style="width:100%">
                        <el-option label="男" value="男" />
                        <el-option label="女" value="女" />
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" label-width="100px" prop="phoneNumber">
                    <el-input v-model="policeInfo.phoneNumber" />
                </el-form-item>
                <el-form-item label="生日" label-width="100px" prop="birthDate">
                    <el-date-picker v-model="policeInfo.birthDate" type="date" placeholder="请选择生日" style="width:100%" />
                </el-form-item>
                <el-form-item label="电子邮件" label-width="100px" prop="email">
                    <el-input v-model="policeInfo.email" />
                </el-form-item>
                <el-form-item label="所属派出所" label-width="100px" prop="stationName">
                    <el-select v-model="policeInfo.policeStation.name" clearable placeholder="请选择所属派出所" style="width: 240px">
                        <el-option v-for="item in stationOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>

                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveOrUpdatePoliceInfo">确定</el-button>
                </span>

            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getPoliceOfficerPage, updatePoliceOfficer, deletePoliceOfficer, addPoliceOfficer } from '@/api/police';
import { ElMessage, ElMessageBox } from 'element-plus';

onMounted(() => {
    fetchData();
});
let flag = true;

const search = () => {
    fetchData();
};

//stationOptions定义

const reset = () => {
    searchParams.name = '';
    searchParams.stationName = '';
    
    fetchData();
};

const stationOptions = ref([]);

const confirmDeleteUser = (row) => {
    ElMessageBox.confirm(`确定要删除警员 ${row.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteUser(row);
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};

const deleteUser = async (row) => {
    const { data } = await deletePoliceOfficer(row.officerId);
    if (data.code === 2000) {
        ElMessage.success(data.message);
    }
    else {
        ElMessage.error(data.message);
    }
    flag = false;
    fetchData(flag);

};

const searchParams = reactive({
    name: '',
    stationName: ''
});


const tableData = ref([]);
const pagination = reactive({
    currentPage: 1,
    pageSize: 5,
    total: 0
});

const dialogFormVisible = ref(false);
const title = ref('添加警员');
const policeInfo = reactive({
    name: '',
    gender: '',
    phoneNumber: '',
    birthDate: '',
    email: '',
    policeStation:{
        name:''
    }
    
});


const rules = {
    name: [
        { required: true, message: '请输入警员名', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    phoneNumber: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[0-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    birthDate: [
        { required: true, message: '请选择生日', trigger: 'change' }
    ],
    email: [
        { required: true, message: '请输入电子邮件', trigger: 'blur' },
        { type: 'email', message: '电子邮件格式不正确', trigger: ['blur', 'change'] }
    ],
    policeStation:{
        name: [
        { required: true, message: '请选择所属派出所', trigger: 'change' }
    ]
    }
    
};

const formatDate = (row, column, cellValue) => {
    const date = new Date(cellValue);
    return date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日';
};

const genderFormat = (row, column, cellValue) => {
    return cellValue === '男' ? '男' : '女';
};

const fetchData = async (flag) => {
    if (flag === false) {
        pagination.currentPage = 1;
    }
    const { data } = await getPoliceOfficerPage({
        currentPage: pagination.currentPage,
        pageSize: pagination.pageSize,
        name: searchParams.name,
        stationName: searchParams.stationName
    });
    if (data.code === 2000) {
        data.data.forEach(item => {
                
                stationOptions.value =  item.stationNameList.map(name => ({
                value: name,
                label: name
            }));
            });

          
        tableData.value = data.data;
        pagination.total = data.total;
        //将data中的stationNameList赋值给stationOptions
       
        
    }
    else {
        ElMessage.error(data.message);
    }
};


const handleDelete = (row) => {
    confirmDeleteUser(row);
};

const handleEdit = (row) => {
    editUser(row);
};

const handleAdd = () => {
    openAddUser();
};

const handleSelectionChange = (val) => {
    console.log(val);
    pagination.total = data.total;
};

const handleSizeChange = (size) => {
    pagination.pageSize = size;
    fetchData();
};

const handleCurrentChange = (page) => {
    pagination.currentPage = page;
    fetchData();
};

const openAddUser = () => {
    dialogFormVisible.value = true;
    title.value = '添加警员';
    Object.assign(policeInfo, {
        name: '',
        gender: '',
        phoneNumber: '',
        birthDate: '',
        email: '',
        stationName: ''
    });
    policeInfoForm.value.resetFields();
};

const policeInfoForm = ref(null);
const saveOrUpdatePoliceInfo = async () => {

    policeInfoForm.value.validate(async (valid) => {
        if (valid) {
            if (title.value === '添加警员') {
                const { data } = await addPoliceOfficer(policeInfo);
               if (data.code === 2000) {
                    ElMessage.success(data.message);
                }
                else { 
                    ElMessage.error(data.message);
                }
            } else {
                const { data } = await updatePoliceOfficer(policeInfo);
                if (data.code === 2000) {
                    ElMessage.success(data.message);
                }
                else {
                    ElMessage.error(data.message);
                }
            }
            dialogFormVisible.value = false;
            fetchData();
        }
    });
    
};

const editUser = (row) => {
    dialogFormVisible.value = true;
    title.value = '编辑警员';
    policeInfoForm.value.resetFields();
    Object.assign(policeInfo, row);
};

onMounted(() => {
    fetchData();
});
</script>

<style >
.el-select {
    width: 160px;
}

.el-pagination {
    margin-top: 20px;
}
</style>
